package com.hyx.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hyx.api.domain.User;
import com.hyx.api.domain.bo.UserBo;
import com.hyx.api.mapper.UserMapper;
import com.hyx.api.service.IMobileLoginService;
import com.hyx.api.utils.ApiTokenUtils;
import com.hyx.api.utils.MD5Util;
import com.hyx.api.utils.base.MobileBaseService;
import com.hyx.api.enums.YesNoEnum;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class MobileLoginServiceImpl extends MobileBaseService implements IMobileLoginService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public AjaxResult login(LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        //校验账号密码是否正确
        LambdaQueryWrapper<User> lqw = Wrappers.lambdaQuery();
        lqw.eq(User::getUsername, loginBody.getUsername()).eq(User::getDelFlag, YesNoEnum.NO.code());
        User user = userMapper.selectOne(lqw);
        if(ObjectUtils.isEmpty(user))
            throw new RuntimeException("当前用户不存在！");
        if (StringUtils.isEmpty(loginBody.getPassword()) ||
                !MD5Util.encrypt32(loginBody.getPassword()).equals(user.getPassword())) {
            throw new ServiceException("账号或密码错误", 500);
        }
        String token = ApiTokenUtils.createToken(user);
        user.setToken(token);
        user.setLoginTime(new Date());
        Long expireTime = System.currentTimeMillis() + ApiTokenUtils.expireTime * 60 * 1000L;
        user.setExpireTime(expireTime);
        userMapper.updateById(user);
        ajax.put("token", token);
        return ajax;
    }

    @Override
    public void logout() {
        super.logout();
        needLogin();
    }

    @Override
    public AjaxResult verify() {
        User user = hasLogin();
        ApiTokenUtils.verifyToken(user);
        return AjaxResult.success();
    }

    @Override
    public AjaxResult loginUserInfo() {
        User user = hasLogin();
        return AjaxResult.success(userMapper.queryUserInfoById(user.getId()));
    }

    public AjaxResult updatePassword(UserBo userBo) {
        User user = hasLogin();
        if(ObjectUtils.isEmpty(userBo.getPassword()))
            throw new RuntimeException("请输入新密码");
        user.setPassword(MD5Util.encrypt32(userBo.getPassword()));
        return userMapper.updateById(user) > 0 ? AjaxResult.success() : AjaxResult.error();
    }
}
